#ifndef __ETHERNET_H__
#define __ETHERNET_H__
#include "IEthernet.h"
#include <EtherCard.h>
#include <JeeLib.h>

byte Ethernet::buffer[700];   

static byte outBuf[256];
//static byte boardIP[] = { 10,0,0,20 }; 
//static byte boardIP[] = { 192,168,4,10 }; 

//static byte broadcastIP[] = { 10,0,0,255 }; 
static byte broadcastIP[] = { 192,168,4,255 }; 
//static byte broadcastIP[] = { 255,255,255,255 }; 
	

class EthernetHW : public IEthernet{
private:
	int length_;
	bool initialized_;
public:
	EthernetHW() : length_(0), initialized_(false) {}
	virtual bool isInitialized() const {
		return initialized_;
	}
	void setup(byte boardIP[], byte myMac[]){
		Serial.println("Ethernet setup ...");
		if (ether.begin(sizeof Ethernet::buffer, myMac) == 0){
			Serial.println( "Failed to access Ethernet controller");
		}
		ether.staticSetup(boardIP);
		Serial.println("Ethernet setup successfull");
		ether.enableBroadcast();
		initialized_=true;
	}

	virtual bool isMessageReady(){
		length_ = ether.packetReceive();
		return length_>0;
	}
	virtual String getMessage(){
		String msg;
		for(int i = 42; i < length_; ++i){
			msg += (char)(Ethernet::buffer[i]);
		}
		return msg;
	}
	virtual void sendMessage(const String& msg){
		if(initialized_){
			Serial.println("ethernet sendMessage " + msg);
			char charBuf[256];
			msg.toCharArray(charBuf, 256); 
			ether.sendUdp (charBuf, msg.length(), 8888, broadcastIP, 8888);	
		}
	}
};

#endif